import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  Animated,
  TextInput,
  TouchableOpacity,
  Dimensions,
} from 'react-native';
import styles from '../auth/indexStyle';
import api from '../../services/api';
import ToastTip from '../global/ToastTip';
import LoadingTip from '../global/LoadingTip';
import CountDownText from '../global/countDown/CountDownText';
import PasswordInput from '../global/PasswordInput';
import dismissKeyboard from 'dismissKeyboard';
let winH = Dimensions.get('window').height;
const Screen = Dimensions.get('window');

class SettingWithdrawPassword extends Component {
    constructor(props) {
		super(props);

		this.state = {
            loadingShow: false,
            curpasswd: '',
            newpasswd: '',
            newrepasswd: '',
            errorText: '', // 错误信息
            code: '', //验证码
		};
	}

    componentWillMount() {
	}

    componentWillUnmount(){
        this.clearTimer && clearTimeout(this.clearTimer);
    }

    async _submitAction(){
        let {code} = this.state;
        let {password} = this.refs.pwdinput;
        if (password.length != 6) {
            this.setState({errorText:'输入6位密码'});
            return;
        }
        let res = await api.post("/housekeeper/changeWithdrawPwd",{pwd:password,code});

        if (res.cd == 1) {
            this.refs.toast.show(res.msg);
            return;
        }

        if (res.data) {
            this.refs.toast.show('设置成功',1000,()=>{
                this.props.navigator.pop();
            });
        }
    }

    _showPass() {

    }

    async _sendCode() {
        let { session } = this.props;

        if(this.state.interval){
            return;
        }

        let res = await api.post("/housekeeper/sendCode",{phone:session.user.phone,type:"CHANGE_WITHDRAW_PWD"});
        this.setState({loadingShow: false, interval:true});

        if(res.cd == 1){
            this.setState({interval:false});
            this.refs.toast.show(res.msg);
            return;
        }

        if(!res.data || res.data.status_code != "OK"){
            this.setState({interval:false});
            if(res.data.status_code == 'isv.BUSINESS_LIMIT_CONTROL'){
                this.refs.toast.show("发送频繁，请稍后重试");
            }else if(res.data.status_code == 'isv.MOBILE_NUMBER_ILLEGAL'){
                this.refs.toast.show("手机号码格式错误");
            }else{
                this.refs.toast.show("发送验证码失败");
            }

			return;
		}

        this.refs.countDownText.start();
        this.refs.toast.show("验证码已发送到您的手机\n10分钟内输入有效", 2000);
    }

    render() {
        let {session:{user:{phone}}} = this.props;
        let {errorText} = this.state;
        return (
            <View style={[styles.container,{backgroundColor:'#f3f3f3'}]} onStartShouldSetResponderCapture={(e) => {
                const focusField = TextInput.State.currentlyFocusedField();
                if (focusField != null && e.nativeEvent.target != focusField){
                    dismissKeyboard();
                }
            }}>
                <ScrollView
                    onScroll={Animated.event(
                      [{ nativeEvent: { contentOffset: { y: this.state.scrollY }}}]
                    )}
                    contentContainerStyle={{backgroundColor:'#f3f3f3'}}
                    scrollEventThrottle={16}
                    keyboardShouldPersistTaps={'always'}
                    keyboardDismissMode='on-drag'>
                    <View style={[styles.toolsContainer,{borderTopWidth:0, borderBottomWidth:0, backgroundColor:'#f3f3f3'}]}>
                        <View style={{backgroundColor:'#fff'}}>
                            <View style={[styles.addBtn, {marginRight:14}]}>
                                <Text style={styles.titleText}>手机号</Text>
                                <View style={{flex:1}}>
                                    <Text style={[styles.titleText,{width:120}]}>{phone.substr(0,3) + '****' + phone.substr(7,4)}</Text>
                                </View>
                            </View>
                            <View style={[styles.addBtn,{paddingRight:0, marginRight:14}]}>
                                <Text style={styles.titleText}>验证码</Text>
                                <TextInput
                                    style={[styles.centerInput,{paddingLeft:0, color:'#7B7B7B'}]}
                                    editable = {true}
                                    clearButtonMode={'while-editing'}
                                    value={this.state.code}
                                    onChangeText={(text)=>{this.setState({code:text})}}
                                    underlineColorAndroid={'transparent'}
                                    placeholder={'请输入短信验证码'}
                                    keyboardType="numeric"
                                    placeholderTextColor={'#B5B5B5'}
                                />
                                <TouchableOpacity onPress={this._sendCode.bind(this)}>
                                    <CountDownText
                                        style={styles.sendCodeText}
                                        disabledStyle={styles.disableSendCodeText}
                                        countType='seconds'
                                        ref='countDownText'
                                        afterEnd={() => {this.setState({interval:false})}}
                                        timeLeft={59}
                                        step={-1}
                                        startText='点击获取验证码'
                                        endText='点击获取验证码'
                                        auto={false}
                                        intervalText={(sec) => sec + '秒后重新获取'}
                                    />
                                </TouchableOpacity>
                            </View>
                        </View>
                        <View style={{alignItems:'center'}}>
                            <View style={{flexDirection:'row',marginTop:22,marginBottom:0,justifyContent:'center',alignItems:'center'}}>
                                <Image source={require('../../../img/hk_password_key_icon.png')} />
                                <Text style={{paddingLeft:10, color: "#565656"}}>
                                    输入新密码
                                </Text>
                            </View>

                            <PasswordInput ref="pwdinput" errorText={errorText} width={Screen.width - 30 - StyleSheet.hairlineWidth * 8}/>
                        </View>
                        <TouchableOpacity onPress={this._submitAction.bind(this)} style={[styles.submitActionPhoneBtn,{marginTop:5,}]}>
                            <Text style={styles.submitActionText}>确认</Text>
                        </TouchableOpacity>
                    </View>
                    <ToastTip ref="toast" offsetY={winH - 64 - 315}/>
                </ScrollView>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
SettingWithdrawPassword = connectHelper(state => state)(SettingWithdrawPassword);

module.exports = SettingWithdrawPassword;
